package com.shengqi.xinnongren.work.ui.user.activities;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;

import com.alipay.sdk.app.PayTask;
import com.google.gson.Gson;
import com.shengqi.xinnongren.R;
import com.shengqi.xinnongren.common.base.BaseMvpActivity;
import com.shengqi.xinnongren.common.utils.LogUtil;
import com.shengqi.xinnongren.common.utils.ToastHelper;
import com.shengqi.xinnongren.work.ui.goods.activities.ChoosePayTypeActivity;
import com.shengqi.xinnongren.work.ui.goods.activities.PayResultActivity;
import com.shengqi.xinnongren.work.ui.goods.model.WeChatPayBean;
import com.shengqi.xinnongren.work.ui.user.presenter.ReChargePayPresenter;
import com.shengqi.xinnongren.work.ui.user.view.ReChargePayView;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

public class ReChargePayActivity extends BaseMvpActivity<ReChargePayView, ReChargePayPresenter> implements ReChargePayView {

    public static final String BROADCAST_WECHAT_PAY = "recharge_pay";
    private static final String EXTRA_MONEY = "money";
    private static final String EXTRA_TYPE = "type";
    @BindView(R.id.iv_alipay)
    ImageView mIvALiPay;
    @BindView(R.id.iv_wechatpay)
    ImageView mIvWeChatPay;

    private int mType;  //1支付宝  2微信
    private String mMoney;

    private MyReceiver mReceiver;
    private int mcType;  //类型  1 充值  2 VIP

    /**
     * @param context
     * @param money   充值金额
     * @param type    类型  1 充值  2 VIP
     */
    public static void start(Context context, String money, int type) {
        Intent intent = new Intent(context, ReChargePayActivity.class);
        intent.putExtra(EXTRA_MONEY, money);
        intent.putExtra(EXTRA_TYPE, type);
        context.startActivity(intent);
    }

    @Override
    protected int setContentLayoutRes() {
        return R.layout.activity_re_charge_pay;
    }

    @Override
    protected void initView() {

        mReceiver = new MyReceiver();
        LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver, new IntentFilter(BROADCAST_WECHAT_PAY));

        if (getIntent() != null) {
            mMoney = getIntent().getStringExtra(EXTRA_MONEY);
            mcType = getIntent().getIntExtra(EXTRA_TYPE, 0);
        }
    }

    @Override
    protected void initData() {

    }

    @OnClick(R.id.ll_alipay)
    void ALiPay() {
        setIvStatus(mIvALiPay, mIvWeChatPay);
        mType = 1;
    }

    @OnClick(R.id.ll_wechatpay)
    void WeChatPay() {
        setIvStatus(mIvWeChatPay, mIvALiPay);
        mType = 2;
    }

    private void setIvStatus(ImageView... imageViews) {
        imageViews[0].setImageResource(R.mipmap.ic_check_checked);
        imageViews[1].setImageResource(R.mipmap.ic_check_normal);
    }

    @OnClick(R.id.tv_confirm_pay)
    void confirmPay() {
        if (mType == 0) {
            ToastHelper.getInstance(this).showWarn("请选择支付方式");
            return;
        }
        mPresenter.pay(mType, mMoney, mcType);
    }

    @Override
    protected ReChargePayPresenter createPresenter() {
        return new ReChargePayPresenter();
    }

    @Override
    public void showLoadingView() {
        showLoadingDialog();
    }

    @Override
    public void hideLoadingView() {
        hideLoadingDialog();
    }

    @Override
    public void onNetworkError() {
        hideLoadingDialog();
    }

    @Override
    public void showPayRes(String data) {
        switch (mType) {
            case 1:
                Runnable payRunnable = () -> {
                    PayTask task = new PayTask(ReChargePayActivity.this);
                    Map<String, String> result = task.payV2(data, true);

                    Message msg = new Message();
                    msg.what = 1;
                    msg.obj = result;
                    mHandler.sendMessage(msg);
                };
                // 必须异步调用
                Thread payThread = new Thread(payRunnable);
                payThread.start();
                break;

            case 2:
                WeChatPayBean bean = new Gson().fromJson(data, WeChatPayBean.class);
                IWXAPI api = WXAPIFactory.createWXAPI(this, bean.getAppid());
                api.registerApp(bean.getAppid());
                PayReq request = new PayReq();
                request.appId = bean.getAppid();
                request.partnerId = bean.getPartnerid();
                request.prepayId = bean.getPrepayid();
                request.packageValue = bean.getPackageX();
                request.nonceStr = bean.getNoncestr();
                request.timeStamp = bean.getTimestamp();
                request.sign = bean.getSign();
                api.sendReq(request);
                break;
        }
    }

    @SuppressLint("HandlerLeak")
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    Map<String, String> result = (Map<String, String>) msg.obj;
                    LogUtil.e("ali  -- " + result.toString());
                    if (result.containsKey("resultStatus")) {
                        if (result.get("resultStatus").equals("9000")) {
                            //成功
                            ReChargeSuccessActivity.start(ReChargePayActivity.this, mType, mMoney);
                        } else if (result.get("resultStatus").equals("8000")) {
                            ToastHelper.getInstance(ReChargePayActivity.this).showSucceed("正在处理中,请稍后查询");
                            finish();
                        } else if (result.get("resultStatus").equals("4000")) {
                            ToastHelper.getInstance(ReChargePayActivity.this).showWarn("订单支付失败");
                        } else if (result.get("resultStatus").equals("5000")) {
                            ToastHelper.getInstance(ReChargePayActivity.this).showWarn("订单重复请求");
                        } else if (result.get("resultStatus").equals("6001")) {
                            ToastHelper.getInstance(ReChargePayActivity.this).showWarn("用户中途取消");
                        } else if (result.get("resultStatus").equals("6002")) {
                            ToastHelper.getInstance(ReChargePayActivity.this).showWarn("网络连接出错");
                        } else if (result.get("resultStatus").equals("6004")) {
                            ToastHelper.getInstance(ReChargePayActivity.this).showWarn("支付结果未知，请稍后查询");
                            finish();
                        } else {
                            ToastHelper.getInstance(ReChargePayActivity.this).showWarn("支付结果未知，请稍后查询");
                            finish();
                        }
                    }
                    break;
            }

        }
    };

    class MyReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            ReChargeSuccessActivity.start(ReChargePayActivity.this, mType, mMoney);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mReceiver);
    }
}
